package com.example.lib_common.logger

import com.example.lib_common.BuildConfig
import com.example.lib_common.utils.MMKVUtil
import com.orhanobut.logger.Logger
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject

object Logger {
    private var isEnable: Boolean = true
    private const val DEFAULT_TAG = "hjw_debug"

    private const val JSON_INDENT: Int = 2

    /**
     * 初始化，需在 Application.onCreate() 调用
     */
    init {
        isEnable = MMKVUtil.get("logger_switch", BuildConfig.DEBUG)
    }

    /**
     * 设置日志开关，并持久化
     */
    fun setEnable(enable: Boolean) {
        isEnable = enable
        MMKVUtil.set("logger_switch", enable)
    }

    /**
     * 获取日志开关状态
     */
    fun isEnable(): Boolean = isEnable

    // ---- 统一入口 ----
    fun v(msg: String, tag: String? = null, tr: Throwable? = null) {
        if (isEnable) Logger.log(Logger.VERBOSE, getTag(tag), msg, null)
    }

    fun d(msg: String, tag: String? = null, tr: Throwable? = null) {
        if (isEnable) Logger.log(Logger.DEBUG, getTag(tag), msg, null)
    }

    fun i(msg: String, tag: String? = null, tr: Throwable? = null) {
        if (isEnable) Logger.log(Logger.INFO, getTag(tag), msg, null)
    }

    fun w(msg: String, tag: String? = null, tr: Throwable? = null) {
        if (isEnable) Logger.log(Logger.WARN, getTag(tag), msg, null)
    }

    fun e(msg: String, tag: String? = null, tr: Throwable? = null) {
        if (isEnable) Logger.log(Logger.ERROR, getTag(tag), msg, null)
    }

    fun json(json: String, tag: String? = null, tr: Throwable? = null) {
        try {
            val json = json.trim { it <= ' ' }
            if (json.startsWith("{")) {
                val jsonObject: JSONObject = JSONObject(json)
                val message = jsonObject.toString(JSON_INDENT)
                d(message, tag, tr)
                return
            }
            if (json.startsWith("[")) {
                val jsonArray = JSONArray(json)
                val message = jsonArray.toString(JSON_INDENT)
                d(message, tag, tr)
                return
            }
            e("Invalid Json", tag, tr)
        } catch (e: JSONException) {
            e("Invalid Json", tag, tr)
        }
    }

    private fun getTag(tag: String?): String {
        return tag?.takeIf { it.isNotEmpty() } ?: DEFAULT_TAG
    }
}